package com.example.springboot.controller;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.example.springboot.common.AuthAccess;
import com.example.springboot.common.CcLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Orders;
import com.example.springboot.entity.User;
import com.example.springboot.service.OrdersService;
import com.example.springboot.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 功能:提供接口返回数据
 */
@RestController//返回json数据
public class WebController {

    @Resource//从spring容器中拿出来
    UserService userService;

    @Resource
    OrdersService ordersService;


    @PostMapping("/login")
    @CcLogs(operation = "用户登录", type = LogType.LOGIN)
    public Result login(@RequestBody User user) {
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword())) {
            return Result.error("数据输入为空");
        }
        user = userService.login(user);
        return Result.success(user);
    }

    @AuthAccess
    @PostMapping("/register")
    @CcLogs(operation = "用户注册", type = LogType.REGISTER)
    public Result register(@RequestBody User user) {
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPassword()) || StrUtil.isBlank(user.getRole())) {
            return Result.error("数据输入存在空值");
        }
//        if(user.getUsername().length() < 8 || user.getUsername().length() > 20){
//            return Result.error("数据输入长度不合法");
//        }
        user = userService.register(user);
        return Result.success(user);
    }

    //重置密码
    @AuthAccess
    @PutMapping("/password")
    public Result password(@RequestBody User user) {
        if (StrUtil.isBlank(user.getUsername()) || StrUtil.isBlank(user.getPhone())) {
            return Result.error("数据输入存在空值");
        }
        userService.resetPassword(user);
        return Result.success();
    }

    /**
     * 获取统计图数据
     *
     * @return 动态数据
     */
    @GetMapping("/charts")
    public Result charts(@RequestParam(defaultValue = "day") String granularity) {
        List<Orders> list = ordersService.list();

        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        DateTimeFormatter outputFormatter;
        TemporalAdjuster temporalAdjuster;

        switch (granularity.toLowerCase()) {
            case "week":
                outputFormatter = DateTimeFormatter.ofPattern("yyyy-'W'ww");
                temporalAdjuster = TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY);
                break;
            case "month":
                outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
                temporalAdjuster = TemporalAdjusters.firstDayOfMonth();
                break;
            default:
                outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                temporalAdjuster = null;
        }

        Map<String, Map<String, BigDecimal>> resultMap = list.stream()
                .filter(orders -> orders.getPayTime() != null && orders.getEquName() != null)
                .collect(Collectors.groupingBy(
                        Orders::getEquName,
                        Collectors.groupingBy(
                                order -> {
                                    LocalDate date = LocalDate.parse(order.getPayTime(), inputFormatter);
                                    if (temporalAdjuster != null) {
                                        date = date.with(temporalAdjuster);
                                    }
                                    return date.format(outputFormatter);
                                },
                                Collectors.mapping(
                                        Orders::getUseCount,
                                        Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)
                                )
                        )
                ));


        return Result.success(resultMap);
    }
}